<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <input v-model.number="firstNumber" type="number" step="20" /> +
      <input v-model.number="secondNumber" type="number" step="20" /> = {{result}}
      <p>
        <animated-integer :value="firstNumber"></animated-integer> +
        <animated-integer :value="secondNumber"></animated-integer> =
        <animated-integer :value="result"></animated-integer>
      </p>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/tween.js/16.3.4/Tween.min.js"></script>
    <script>
      Vue.component("animated-integer", {
        template: "<span>{{tweeningValue}}</span>",
        props: {
          value: {
            type: Number,
            required: true,
          },
        },
        data: function () {
          return {
            tweeningValue: 0,
          };
        },
        watch: {
          value: function (newVal, oldVal) {
            this.tween(oldVal, newVal);
          },
        },
        mounted: function () {
          this.tween(0, this.value);
        },
        methods: {
          tween: function (startVal, endVal) {
            var vm = this;
            function animate() {
              if (TWEEN.update()) {
                requestAnimationFrame(animate);
              }
            }

            new TWEEN.Tween({ tweeningValue: startVal })
              .to({ tweeningValue: endVal }, 500)
              .onUpdate(function () {
                vm.tweeningValue = this.tweeningValue.toFixed(0);
              })
              .start();

            animate();
          },
        },
      });

      new Vue({
        el: "#app",
        data: {
          firstNumber: 10,
          secondNumber: 20,
        },
        computed: {
          result: function () {
            return this.firstNumber + this.secondNumber;
          },
        },
      });
    </script>
  </body>
</html>
